# -*- coding: utf-8 -*-
# @Date   : 2020/3/20
# @File   : R60_PersonalInventoryBusinessGuaranteeTypeCheck_CF.py
# @Author : zhaochen

'''eof
name:申请人存量业务保证类型校验
code:R60_PersonalInventoryBusinessGuaranteeTypeCheck_CF
tableName:
columnName:
groups:业务其他规则校验
dependencies:EG_DSJ
type:常用指标
datasourceType:在线指标
description:
eof'''

import sys
import pandas as pd
import json
from datetime import datetime

reload(sys)
sys.setdefaultencoding('utf-8')


def get_age(str1):
    try:
        date1 = datetime.now()
        date2 = date_format(str1)
        diff_year = date1.year - date2.year
        diff_month = date1.month - date2.month
        diff_day = date1.day - date2.day
        age = diff_year + diff_month / 12.0 + diff_day / 365.0
        return age
    except:
        return u'缺失值'


# 统一转成datetime对象，只能转年月日的字符串
def date_format(time):
    import re
    r = re.compile(r'\D+')
    try:
        date = datetime.strptime(time, '%Y.%m.%d')
    except:
        try:
            date = datetime.strptime(time, '%Y-%m-%d')
        except:
            try:
                date = datetime.strptime(time, '%Y/%m/%d')
            except:
                try:
                    tmp = r.sub('', time)
                    date = datetime.strptime(tmp, '%Y%m%d')
                except:
                    date = None
    return date


def float_check(target):
    try:
        float(target)
        return True
    except:
        return False


def get_business_type_contract_no(abnormalloan, contractNo):
    for i in abnormalloan:
        try:
            customertype = i["customerType"]
            businessType = i["businessType"]
            contratctNo = i["contratctNo"]
        except:
            continue
        if customertype == "2":
            if contratctNo == contractNo:
                return businessType
    return None


def R60_PersonalInventoryBusinessGuaranteeTypeCheck_CF():
    null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']
    vouchtypecodde_list = ["001001001001", "001001001002", "001001002001", "001001003001", "001003001001",
                           "001003001002", "001003001003", "001004001001", "001004001002", "001004002001",
                           "001004002002"]
    rejectList = [u'信用', u'企业保证', u'自然人保证', u'境外银行保证']
    rejectListTwo = ['010001', '010002', '010003']
    rejectListThree = ['10302030', '10302015', '10302020', '10302010']
    abnormalloan = json.loads(ratingRequest.get("abNormalloan"))
    resultList = []
    if abnormalloan not in null_type_list and isinstance(abnormalloan, list):
        if len(abnormalloan) >= 1:
            for i in abnormalloan:
                try:
                    vouchtype = i.get("vouchType")
                    customertype = i.get("customerType")
                    vouchtypecodde = i.get("vouchTypeCode")
                    businessType = i["businessType"]
                    balance = i.get("balance")
                    contratctNo = i.get("contratctNo")
                except:
                    continue
                if customertype not in null_type_list:
                    if customertype == "0":
                        if businessType in ("107010", "11104010", "10101025"):
                            resultList.append(businessType)
                            continue
                        if vouchtype == u"信用":
                            if businessType == '11103030' and float_check(balance) and float(balance) == 0:
                                resultList.append(u"微粒贷")
                            elif businessType in null_type_list and float_check(balance) and float(balance) != 0:
                                resultList.append(u"信用")
                            elif businessType in null_type_list and float_check(balance) and float(balance) == 0:
                                business = get_business_type_contract_no(abnormalloan, contratctNo)
                                if business == "11103030":
                                    resultList.append(u"微粒贷")
                                else:
                                    resultList.append(u"信用")
                            elif businessType not in null_type_list and businessType != "11103030":
                                resultList.append(u"信用")
                            else:
                                resultList.append(u"其他")

                        if vouchtype == u"保证" and vouchtypecodde in rejectListTwo:
                            resultList.append(u"保证"+vouchtypecodde)
                        if vouchtype == u"抵押":
                            resultList.append(u"抵押")
                        if vouchtype not in null_type_list and vouchtypecodde not in null_type_list:
                            if vouchtype == u"质押" and vouchtypecodde in vouchtypecodde_list:
                                resultList.append(u"质押")
                            elif vouchtype == u"质押":
                                resultList.append(u"质押"+vouchtypecodde)
                            else:
                                resultList.append(u"无触碰项")
                        else:
                            resultList.append(u'无触碰项')
                else:
                    resultList.append(u'customertype为空')
        else:
            resultList.append(u"表为空")
    else:
        raise RuntimeError("网贷传输的数据格式错误或者为空")

    return u','.join(resultList)


if __name__ == "__main__":
    ratingRequest = {"legalPersonIdCard": "500101199202192411", "timeLimit": "12", "abNormalloan": [
        {"vouchType": u"信用", "customerType": "0", "vouchTypeCode": "010001", "businessType": "", "balance": "0",
         "contratctNo": "111"},
        {"vouchType": u"信用", "customerType": "0", "vouchTypeCode": "010001", "businessType": "107010", "balance": "0",
         "contratctNo": "0"},
        {"vouchType": u"信用", "customerType": "2", "vouchTypeCode": "010001", "businessType": "11103030", "balance": "0",
         "contratctNo": "111"}
    ]}
    aa = R60_PersonalInventoryBusinessGuaranteeTypeCheck_CF()
    print aa

result = R60_PersonalInventoryBusinessGuaranteeTypeCheck_CF()
